package com.ruoyi.web.controller.api.recipe;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.NoLoginRequired;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.WxLoginEntity;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.framework.config.WxAppConfig;
import com.ruoyi.framework.jwt.utils.JwtUtils;
import com.ruoyi.framework.shiro.service.SysPasswordService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.controller.api.APIController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@Api("用户登录")
@RestController
public class LoginController extends APIController {
    @Autowired
    private WxAppConfig wxAppConfig;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysPasswordService passwordService;

    @ApiOperation("微信小程序登录")
    @ApiImplicitParam(name = "jsCode", value = "用户登录凭证", required = true, dataType = "String", dataTypeClass = String.class)
    @GetMapping("/api/login")
    @NoLoginRequired
    public AjaxResult wxLogin(String jsCode) {
        logger.info("微信小程序登录：" + jsCode);
        try {
            WxLoginEntity wxLoginEntity = getWxOpenId(jsCode);
            String unionid = wxLoginEntity.getUnionId();
            String openid = wxLoginEntity.getOpenId();
            SysUser user = userService.selectUserByOpenId(openid);
            if (user == null) {
                user = new SysUser();
                String uuid = IdUtils.simpleUUID();
                user.setLoginName(uuid);
                user.setUserName(uuid);
                user.setUserType("01");
                user.setSex("2");
                user.setSalt(ShiroUtils.randomSalt());
                user.setPassword("123456");
                user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
                user.setPwdUpdateDate(DateUtils.getNowDate());
                user.setCreateBy("API");
                user.setOpenId(openid);
                user.setUnionId(unionid);
                userService.insertUser(user);
            }
            if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
                return AjaxResult.error("对不起，您的账号已被删除!");
            }

            if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
                return AjaxResult.error("用户已封禁，请联系管理员!");
            }

            String token = JwtUtils.createToken(user.getUserName(), user.getPassword());
            AjaxResult result = AjaxResult.success("登录成功,请妥善保管您的token信息");
            result.put("token", token);
            result.put("openId", openid);
            return result;
        } catch (Exception e) {
            logger.error("登录失败：" + e.getMessage(), e);
            return AjaxResult.error("登录失败!");
        }
    }

    private WxLoginEntity getWxOpenId(String jsCode) throws Exception {
        //向微信服务器发送请求获取用户信息
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        String params = StringUtils.format("appid={}&secret={}&js_code={}&grant_type=authorization_code", wxAppConfig.getAppId(), wxAppConfig.getAppSecret(), jsCode);
        String jsonStr = HttpUtils.sendGet(url, params);
        if (StringUtils.isEmpty(jsonStr)) {
            throw new Exception("服务器无响应：" + url);
        }

        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String session_key = (String) jsonObject.get("session_key");
        String openid = (String) jsonObject.get("openid");
        String unionid = (String) jsonObject.get("unionid");
        if (StringUtils.isEmpty(openid)) {
            String errmsg = (String) jsonObject.get("errmsg");
            throw new Exception("未获取到openid：" + errmsg);
        }
        WxLoginEntity wxLoginEntity = new WxLoginEntity();
        wxLoginEntity.setCode(jsCode);
        wxLoginEntity.setSessionKey(session_key);
        wxLoginEntity.setOpenId(openid);
        wxLoginEntity.setUnionId(unionid);
        return wxLoginEntity;
    }
}
